package com.example.schoolhelp.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 项目名称:  i尚社区
 * 包:      com.ifation.community.utils.net
 * 类名称:   CommonToolUtils
 * 类描述:   工具类
 * 创建人:   秦彬
 * 创建时间:  2016-11-30 10:22
 * 修改人:
 * 修改时间:
 * 修改备注:
 * 版本:    v1.0
 */
public class CommonToolUtils {

    /**
     * 正则判断：用于手机号输入判断
     *
     * @param values    内容
     * @param reference 需要匹配的内容
     * @return 内容与需要匹配的不符合 返回false ，反之true
     */
    public static boolean regularExpression(String values, String reference) {
        if (!"".equals(values) && !"".equals(reference)) {
            Pattern p = Pattern.compile(reference);
            Matcher m = p.matcher(values);
            return m.matches();
        } else {
            return false;
        }
    }

    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 判断是否有可用网络 无线和3G
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        boolean net = isOpenNetWork(context);
        if (net) {
            ConnectivityManager cManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cManager != null) {
                cManager.getActiveNetworkInfo().isAvailable();
                NetworkInfo[] info = cManager.getAllNetworkInfo();

                if (info != null) {
                    for (int i = 0; i < info.length; i++) {
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }

            }
            return false;
        } else {
            return false;
        }

    }

    /**
     * 判断是否打开网络
     *
     * @param context 上下文
     * @return
     */
    public static boolean isOpenNetWork(Context context) {
        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {

                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    /**
     * 获取当前格式化日期
     *
     * @return
     */
    public static String getCurrentFormatTime() {
        //当前时间
        SimpleDateFormat strTime = new SimpleDateFormat("yyyyMMddHHmmss");
        String longtime = strTime.format(new Date());

        return longtime;

    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static String getCurrentVersion(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return "";

    }

    //压缩图片
    public static Bitmap improveImage(Bitmap bitMap, String path) {
        Bitmap yuanbitMap = bitMap;
        // 设置图片的大小
        int width = yuanbitMap.getWidth();
        int height = yuanbitMap.getHeight();
        // 设置想要的大小
        int newWidth = 360;
        int newHeight = 640;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float min = Math.min(scaleWidth, scaleHeight);
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(min, min);
        yuanbitMap = Bitmap.createBitmap(yuanbitMap, 0, 0, width, height,
                matrix, true);
        // 得到新的图片

        if (height > width) {
            Log.e("得到新的图片heighe", "得到新的图片成功heighe");
            bitMap = Bitmap.createBitmap(bitMap, 0, (height - width) / 2,
                    width, width, matrix, true);
        } else {
            Log.e("得到新的图片width", "得到新的图片成功width");
            bitMap = Bitmap.createBitmap(bitMap, (width - height) / 2, 0,
                    height, height, matrix, true);
        }

        try {
            //保存图片
            Log.e("保存图片", "保存图片成功");
            FileOutputStream out = new FileOutputStream(path);
            bitMap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return yuanbitMap;
    }

    // Gps是否可用
    public static final boolean isGpsEnable(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }


    public static void toOpenGPSSettings(Context context, Fragment activity) {
        LocationManager alm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(context, "GPS模块正常", Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(context, "请开启位置信息！", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        activity.startActivityForResult(intent, 1); //此为设置完成后返回到获取界面
    }

    public static boolean checkPermission(Context context, String permission) {
        PackageManager pm = context.getPackageManager();
        boolean isTure = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission(permission, context.getPackageName()));
        return isTure;
    }

    /**
     * 设置间隔一段时间的设置
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClicke() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 设置只可点击一次
     */
    public static int ClickTime = 0;

    public static boolean isFastDoubleClick() {

        if (ClickTime == 0) {
            ClickTime = 1;
            return true;
        } else {
            return false;
        }

    }

    /**
     * 判断是否安装摸个第三方应用
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

    }

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }

        return false;
    }

    /**
     * 压缩图片
     *
     * @param image
     * @return
     */
    public static Bitmap compress(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 512) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;

        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 400f;// 这里设置高度为800f
        float ww = 240f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;

        Log.e("inSampleSize", be + "");
        newOpts.inSampleSize = be;// 设置缩放比例
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;// 降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;
    }

    /**
     * 图片转字节
     *
     * @param bm
     * @return
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * ms转日期
     *
     * @param pattern  格式 “yyyyMMdd”
     * @param dateTime 毫秒
     * @return
     */
    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 返回屏幕宽度
     *
     * @return Width 宽度
     */
    @SuppressWarnings("deprecation")
    public static int getWidth(Context mContext) {

        WindowManager wManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int Width = wManager.getDefaultDisplay().getWidth();
        return Width;
    }

    /**
     * 返回屏幕高度
     *
     * @return Width 宽度
     */
    @SuppressWarnings("deprecation")
    public static int getHeight(Context mContext) {

        WindowManager wManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int Width = wManager.getDefaultDisplay().getHeight();
        return Width;
    }

    /**
     * 计算某年某月多少天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static int daysByMonth(int year, int month) {

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 车牌号格式：汉字 + A-Z + 位A-Z或-
     * （只包括了普通车牌号，教练车和部分部队车等车牌号不包括在内）
     * 1.常规车牌号：仅允许以汉字开头，后面可录入六个字符，由大写英文字母和阿拉伯数字组成。如：粤B12345；
     * 2.最后一个为汉字的车牌：允许以汉字开头，后面可录入六个字符，前五位字符，由大写英文字母和阿拉伯数字组成，而最后一个字符为汉字，汉字包括“挂”、“学”、“警”、“港”、“澳”。如：粤Z1234港。
     * 3.新军车牌：以两位为大写英文字母开头，后面以5位阿拉伯数字组成。如：BA12345。
     */
    public static boolean isCarNumber(String carNumber) {

        String carnumRegex = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$";
        if (TextUtils.isEmpty(carNumber)) {
            return false;
        } else {
            return carNumber.matches(carnumRegex);
        }
    }


    /**
     *
     * 获取屏幕状态栏高度
     */
    public static int getStatusHeight(Activity activity) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        activity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass
                        .getField("status_bar_height").get(localObject)
                        .toString());
                statusHeight = activity.getResources()
                        .getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    /**
     * 判断是否需要打开权限
     *
     * @param context
     * @param permission
     *            需要处理的权限
     * @return
     */
    public static boolean selfPermissionGranted(Context context,
                                                String permission) {
        boolean result = true;
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                if (getTargetVersion(context) >= 23) {
                    result = ContextCompat.checkSelfPermission(context,
                            permission) == PackageManager.PERMISSION_GRANTED;
                } else {
                    result = PermissionChecker.checkSelfPermission(context,
                            permission) == PermissionChecker.PERMISSION_GRANTED;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     * 获取manifest targetsdk
     *
     * @param context
     * @return
     */
    public static int getTargetVersion(Context context) {
        try {
            final PackageInfo info = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return info.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return 0;
    }

}
